package com.sky.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.EmployeeCreateException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import java.util.List;
import java.util.Objects;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // TODO 后期需要进行md5加密，然后再进行比对
        String mdPpassword = DigestUtils.md5DigestAsHex(password.getBytes());

        //密码比对
        if (!mdPpassword.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定（账号状态）
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public void create(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        Integer countByUserName = employeeMapper.SelectCountByUserName(employee.getUsername());
        if (countByUserName > 0){
            throw new EmployeeCreateException(MessageConstant.REPEAT_USER_NAME);
        }
        this.checkEmployee(employeeDTO);
        //将重复的属性进行copy
        BeanUtils.copyProperties(employeeDTO,employee);
//      employee.setUsername(employeeDTO.getUsername());
//      employee.setName(employeeDTO.getName());
//      employee.setPhone(employeeDTO.getPhone());
//      employee.setSex(employeeDTO.getSex());
//      employee.setIdNumber(employeeDTO.getIdNumber());
        String digestAsHex = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        employee.setPassword(digestAsHex);
        employee.setStatus(StatusConstant.ENABLE);
//      employee.setCreateTime(LocalDateTime.now());
//      employee.setUpdateTime(LocalDateTime.now());
//      TODO 创建人的ID和更新人的ID  通过JWT获得
//      employee.setCreateUser(BaseContext.getCurrentId());
//      employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.insertEmployee(employee);
    }

    @Override
    public PageResult selectEmployeeByName(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        List<Employee> list = employeeMapper.selectEmployeeByName(employeePageQueryDTO.getName());
        PageInfo<Employee> pageInfo = PageInfo.of(list);
        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
//      PageResult pageResult = new PageResult();
//      pageResult.setTotal(pageInfo.getTotal());
//      pageResult.setRecords(pageInfo.getList());
//      return pageResult;
    }

    @Override
    public void updateStatusById(Long id, Integer status) {
        Employee employee = employeeMapper.selectEmployeeById(id);
        employee.setStatus(status);
        employeeMapper.update(employee);
    }

    @Override
    public Employee queryById(Long id) {
        Employee employee = employeeMapper.selectEmployeeById(id);
        employee.setPassword(null);
        return employee;
    }

    @Override
    public void update(EmployeeDTO employeeDTO) {
        Integer count = employeeMapper.SelectCountByIdNotSelf(employeeDTO.getId(),employeeDTO.getUsername());
        if( count > 0){
            throw new EmployeeCreateException(MessageConstant.REPEAT_USER_NAME);
        }
        this.checkEmployee(employeeDTO);
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employeeMapper.update(employee);
    }

    private void checkEmployee(EmployeeDTO employeeDTO) {
        if (Objects.isNull(employeeDTO.getPhone())||employeeDTO.getPhone().length() != 11){
            throw new EmployeeCreateException(MessageConstant.ERROR_PPHONE);
        }
        if (Objects.isNull(employeeDTO.getIdNumber())||employeeDTO.getIdNumber().length() != 18){
            throw new EmployeeCreateException(MessageConstant.ERROR_ID_NUMBER);
        }
    }


}
